package org.sword.wechat4j.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.log4j.Logger;
import org.sword.wechat4j.api.WechatClient;
import org.sword.wechat4j.api.request.material.Cgi_binMediaUploadimgFilepost;
import org.sword.wechat4j.api.response.material.MediaInfo;
import org.sword.wechat4j.type.ErrorCode;

import java.io.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wxc on 2016/8/16 0016.
 */
public class ImageUpload {

    private static SingletonHttpClient client = SingletonHttpClient.getDefaultClient();

    private static final Logger log = Logger.getLogger(ImageUpload.class);

    /**
     *
     * @param content 源html
     * @param list 空集合，用于灌注结果
     * @return 适合直接上传的html
     */
    public static String replaceImageUrlAfterUpload(String content, List<MediaInfo> list,
                                                    WechatClient wxclient, String token) {
        Pattern p = Pattern.compile("<img.*?src=\"(.*?)[jpg|jpeg|gif|png]\"");
                Matcher m = p.matcher(content);
        while (m.find()) {
            String has = m.group();
            has = has.substring(has.indexOf("src=\"") + 5);
            has = has.substring(0, has.indexOf("\""));

            if (StringUtils.isEmpty(has))
                continue;
            String fileName = String.valueOf(System.currentTimeMillis()) + ".";
            if (has.endsWith("jpg"))
                fileName += "jpg";
            else if (has.endsWith("jpeg"))
                fileName += "jpeg";
            else if (has.endsWith("gif"))
                fileName += "gif";
            else
                fileName += "png";
            File file = getImageFile(has, fileName);

            if (file == null || file.length() == 0) {
                log.error("图片读取失败，url:" + has);
                continue;
            }
            log.info("file length:" + file.length());
            Cgi_binMediaUploadimgFilepost imgPost = new Cgi_binMediaUploadimgFilepost();
            imgPost.setMedia(file);
            MediaInfo info;
            try {
                info = wxclient.execute(imgPost, token);
                if (info.isSuccess()) {
                    content = content.replace(has, info.getUrl());
                    list.add(info);
                }else{
                    log.error("上传失败！原因：" + ErrorCode.mean(info.getErrcode()));
                }
            } catch (IOException e) {
                log.error("上传请求失败！", e);
            }
        }
        return content;
    }

    public static File getImageFile(String url, String name) {
        File file = null;
        try {
            file = new File(name);
            FileOutputStream out = new FileOutputStream(file);
            HttpEntity stream = client.getStream(url);
            stream.writeTo(out);
        } catch (IOException e) {
            log.error("图片读取失败，url:" + url, e);
        }
        return file;
    }
}
